<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import axios from 'axios';
import * as echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'
import {salecount} from "@/api/commodity/commodity";


export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    }
  },
  data() {
    return {
      chart: null,
      data: []
    }
  },
  mounted() {
    this.showsalecount()
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },

  methods: {
    showsalecount() {
      let showsalecount = echarts.init(this.$el, 'macarons');
      salecount().then(response => {
        let cnames = [];
        let counts = [];
        let array = response.data;
        array.sort((a, b) => b.count - a.count);

        for (let i in array) {
          cnames.push(array[i].cname);
          counts.push(array[i].count);
        }

        let seriesData = cnames.map((name, index) => {
          return {name: name, value: counts[index]};
        });

        showsalecount.setOption({
          title: {
            text: '商品订单销售量占比',
            left: 'center'
          },
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b} : {c} ({d}%)'
          },
          toolbox: {
            feature: {
              dataView: {show: true, readOnly: false},
              restore: {show: true},
              saveAsImage: {show: true}
            }
          },
          legend: {
            left: 'center',
            bottom: '10',
            type: 'scroll',
            max: 5,
            data: cnames
          },
          series: [
            {
              name: '产品销售量',
              type: 'pie',
              radius: '70%',
              center: ['50%', '50%'],
              label: {
                show : false,
              },
              labelLine: {
                show : false,
              },
              data: seriesData,
              animationEasing: 'cubicInOut',
              animationDuration: 2600
            }
          ]
        });
      });

    }

  }


}
</script>
